var UUID = require('../../utils/Math.uuid')
var KL = require('../../template/zakl/kouling')
var {cutStringSum, keepTwoDecimalFull, formatDate} = require('../../utils/util')
var app = getApp()

var ordertype, dateArr, dateChArr, timeArr, dateWeekArr, timeChArr,
  mid, fid, stationId, storeId, breadType, queryDate,
  ordersource,
  distype = 'NORMAL'

Page({
  data: {
    tipsOK: '1',
    balanceUsed: '0'
  },
  onLoad: function (options) {
    ordertype = ''

    if (options.type) {
      ordertype = options.type
    }

    ordersource = options.orderSource || 'NORMAL'

    this.setData({
      ordertype: ordertype,
      usernotes: ''
    })

    KL.init(this)

    var goods = []

    if (options.orderinfo) {
      stationId = options.stationId
      storeId = options.storeId
      breadType = options.breadType
      queryDate = options.queryDate
      if (ordertype === 'cake') {
        var cakedata = JSON.parse(decodeURIComponent(options.orderinfo))
        goods = cakedata.goodslist
        for (var i = 0; i < goods.length; i++) {
          goods[i].boardcard = 'Happy Birthday'
        }
        mid = cakedata.mid
        fid = cakedata.fid
        this.setData({
          partsnotes: [
            '每套标配餐具：一个餐盘、一把餐勺',
            '赠送一只工艺蜡烛',
            '若不填写巧克力牌则为默认(限8字以内)'
          ]
        })
      } else {
        goods = JSON.parse(decodeURIComponent(options.orderinfo))
      }
    }

    this.setData({
      goods: goods,
      codeval: '',
      codeStatus: 0,
      codeprice: 0,
      balanceStatus: 0,
      pointStatus: 1,
      computeId: null,
      couponName: '',
      cardNo: null,
      cardPwd: null,
      freeSecret: false
    })

    dateArr = []
    dateChArr = []
    timeArr = []
    var address = ''
    if (options.address) {
      address = JSON.parse(decodeURIComponent(options.address))
      this.setData({
        address: address
      })
      this.loadSendTime()
      this.loadKLAndPrice()
    }
    else {
      if (app.globalData.address) {
        address = app.globalData.address
        this.setData({
          address: address
        })
        this.loadSendTime()
        this.loadKLAndPrice()
      }
      else {
        wx.switchTab({
          url: '../index/index',
        })
      }
    }
  },
  onShow: function () {
    if (app.globalData.address.ADDRESS !== this.data.address.ADDRESS || app.globalData.address.ID !== this.data.address.ID) {
      app.globalData.needClearBreadCar = '1'
      app.globalData.needClearCakeCar = '1'
      wx.navigateBack()
      return
    }

    if (app.globalData.tempCoupon) {
      this.setData({
        computeId: app.globalData.tempCoupon.id,
        couponName: app.globalData.tempCoupon.name,
        codeStatus: 0,
        codeval: ''
      })
      app.globalData.tempCoupon = null
      this.loadKLAndPrice()
    }

    if (app.globalData.tempCashCard) {
      this.setData({
        cardNo: app.globalData.tempCashCard.cardNo,
        cardPwd: app.globalData.tempCashCard.cardPwd
      })
      app.globalData.tempCashCard = null
      this.loadKLAndPrice()
    }

    if (app.globalData.tempUseBalance === '1') {
      this.setData({
        balanceUsed: '1',
        balanceStatus: 1
      })
      app.globalData.tempUseBalance = null
      this.loadKLAndPrice()
    }
  },

  agreeMatter: function () {
    if (this.data.tipsOK === '1') {
      this.setData({
        tipsOK: '0'
      })
    }
    else {
      this.setData({
        tipsOK: '1'
      })
    }
  },
  balanceUsedAction: function () {
    if (this.data.balanceUsed === '1') {
      this.setData({
        balanceUsed: '0',
        balanceStatus: 0,
      })
      this.loadKLAndPrice()
    }
    else {
      if (this.data.freeSecret === true) {
        this.setData({
          balanceUsed: '1',
          balanceStatus: 1
        })
        this.loadKLAndPrice()
      }
      else {
        wx.navigateTo({
          url: '../my/balance/password/password?target=check',
        })
      }
    }
  },
  maidianChange: function (e) {
    var pointstatus = 0
    if (e.detail.value === true) {
      pointstatus = 1
    }
    this.setData({
      pointStatus: pointstatus
    })
    this.loadKLAndPrice()
  },
  chooseCoupon: function () {
    var couponlist
    if (ordertype === 'cake') {
      couponlist = this.data.extrainfo.PROMOTION
    }
    else {
      couponlist = JSON.stringify(this.data.extrainfo.PROMOTION)
    }

    wx.navigateTo({
      url: '../my/coupon/choose?coupon=' + couponlist + '&selected=' + this.data.computeId,
    })
  },
  useCashCard: function () {
    wx.navigateTo({
      url: '../my/cashcard/cashcard',
    })
  },
  loadSendTime: function (senddate = '') {
    var url
    var property = {}
    var params = {}
    var cityid = app.globalData.address.CITYID
    var reqMethod = 'POST'

    if (ordertype === 'bread') {
      if (ordersource === 'BREAKFAST') {
        url = `/yuanmai_we/breakfast/delivery/time/get/10216/${queryDate}`
        reqMethod = 'GET'
      } else {
        url = '/yuanmai_we/product/deliverytime/list'
        var curdate = formatDate(new Date(), 'yyyy-MM-dd HH:mm:ss')
        var location = app.globalData.address.LOCATION
        var products = []
        for (var i = 0; i < this.data.goods.length; i++) {
          var goodsinfo = {
            id: this.data.goods[i].ID,
            STOCK: this.data.goods[i].STOCK
          }
          products.push(goodsinfo)
        }
        property = {
          "DTS": "DRHR",
          "date": curdate,
          "ORDERSTARTDAY": breadType === '3' ? "TOMORROW" : "TODAY",
          "CITYID": cityid,
          "ORDERSOURCE": ordersource,
          "productList": products,
          "location": location
        }
      }
    }
    else if (ordertype === 'cake') {
      url = '/yuanmai_we/mcake/delivery/time/get'
      var sku_arr = []
      for (var i = 0; i < this.data.goods.length; i++) {
        sku_arr.push(this.data.goods[i].sku)
      }
      var skustr = sku_arr.join(',')
      property = {
        cityId: cityid,
        stationId: stationId,
        sku: skustr,
        fid: fid,
        mid: mid,
        date: senddate
      }
    }

    if (ordersource !== 'BREAKFAST') {
      if (storeId) {
        property['STOREID'] = storeId
      }

      params = {
        datas: JSON.stringify(property),
        __zaofans: true
      }
    }

    app.request(url, params, reqMethod).then(this.loadSendTimeCallBack.bind(this))
  },
  loadSendTimeCallBack: function (res) {
    if (ordertype === 'bread') {
      this.dealResForBread(res)
    }
    else {
      this.dealResForCake(res)
    }
  },
  dealResForBread: function (res) {
    dateArr = []
    dateChArr = []
    timeArr = []
    dateWeekArr = []
    timeChArr = []
    for (var i = 0; i < res.length; i++) {
      var datetime = res[i].date
      var chstr = ''
      if (res[i].fastDispFlag) {
        chstr = '45分钟极速送达'
      }
      else {
        chstr = res[i].DR + ' ' + res[i].dayOfWeek
      }
      if (dateWeekArr.indexOf(chstr) >= 0) {
        timeArr[timeArr.length - 1].push(res[i].HR)
        timeChArr[timeChArr.length - 1].push(res[i].HR)
      }
      else {
        if (res[i].fastDispFlag) {
          distype = 'IMMEDIATE'
          dateWeekArr.push('45分钟极速送达')
          timeChArr.push([''])
        }
        else {
          var str = res[i].DR + ' ' + res[i].dayOfWeek
          distype = 'NORMAL'
          dateWeekArr.push(str)
          timeChArr.push([res[i].HR])
        }

        timeArr.push([res[i].HR])
        dateArr.push(datetime)
        dateChArr.push(res[i].DR)
      }
    }
    var dateTimeSets = [
      dateWeekArr,
      timeChArr[0]
    ]

    this.setData({
      timeIndex: [0, 0],
      dateTimeSets: dateTimeSets
    })
  },
  dealResForCake: function (res) {
    if (res.data.dispDate) {
      dateArr = []
      dateChArr = []
      for (var i = 0; i < res.data.dispDate.length; i++) {
        dateArr.push(res.data.dispDate[i].date)
        dateChArr.push(res.data.dispDate[i].date + ' ' + res.data.dispDate[i].week)
      }
    }
    if (res.data.dispTime) {
      timeArr = []
      for (var i = 0; i < res.data.dispTime.list.length; i++) {
        for (var j = 0; j < res.data.dispTime.list[i].list.length; j++) {
          var timestr = res.data.dispTime.list[i].hour + ':' + res.data.dispTime.list[i].list[j].min
          timeArr.push(timestr)
        }
      }
    }
    var dateTimeSets = [
      dateChArr,
      timeArr
    ]
    var timeIndex = [0, 0]
    if (this.data.timeIndex) {
      timeIndex = this.data.timeIndex
      timeIndex[1] = 0
    }
    this.setData({
      timeIndex: timeIndex,
      dateTimeSets: dateTimeSets
    })
  },
  loadKLAndPrice: function () {
    var products = []
    var totalcount = 0
    for (var i = 0; i < this.data.goods.length; i++) {
      var num
      if (this.data.goods[i].COUNT !== undefined) {
        num = +this.data.goods[i].COUNT
      }
      else {
        num = +this.data.goods[i].num
      }
      var productinfo = {
        id: this.data.goods[i].ID,
        num: num
      }
      products.push(productinfo)
      totalcount += num
    }
    this.setData({
      totalcount: totalcount
    })
    var property
    var params
    var url
    if (ordertype === 'cake') {
      url = '/yuanmai_we/mcake/order/compute'
      var address = {
        "location": this.data.address.LOCATION,
        "city": this.data.address.CITYNAME,
        "county": this.data.address.COUNTYNAME,
        "address": this.data.address.ADDRESS,
        "hasAddress": !!this.data.address.ADDRESS,
      }
      property = {
        "pointStatusBB": true,
        "pointStatus": this.data.pointStatus,
        "codeStatus": 0,
        "computeId": this.data.computeId,
        "codeValue": null,
        "showPromotion": false,
        "balanceStatus": this.data.balanceStatus,
        "balanceStatusBB": false,
        "cardNo": this.data.cardNo,
        "cardPwd": this.data.cardPwd,
        "meals": products
      }
      params = {
        datas: JSON.stringify(property),
        address: JSON.stringify(address),
        __zaofans: true
      }
    } else {
      url = '/yuanmai_we/orders/orderFormOrder/compute'
      property = {
        "pointStatusBB": true,
        "pointStatus": this.data.pointStatus,
        "codeStatus": this.data.codeStatus,
        "computeId": this.data.computeId,
        "codeValue": this.data.codeval,
        "showPromotion": false,
        "balanceStatus": this.data.balanceStatus,
        "meals": products,
        "orderSource": ordersource,
        "balanceStatusBB": true
      }
      params = {
        datas: JSON.stringify(property),
        __zaofans: true
      }
    }
    app.showLoading()
    app.request(url, params).then(this.loadKLAndPriceCallBack.bind(this))
  },
  loadKLAndPriceCallBack: function (res) {
    app.hideLoading()
    if (ordertype === 'bread') {
      if (res.RESULT === 'SUCCESS') {
        res.PAYTATOL = keepTwoDecimalFull(res.PAYTATOL)
        res.DELIVERPAY = keepTwoDecimalFull(res.DELIVERPAY)
        res.TOTALPRICE = keepTwoDecimalFull(res.TOTALPRICE)

        if (res.PROMOTION) {
          res.couponNum = res.PROMOTION.AVAILABLEPROMOTIONS.length
        } else {
          res.couponNum = 0
        }

        var status
        if (parseFloat(res.CODEVALUE) > 0) {
          status = 1
        } else {
          status = 0
        }

        var freeSecret = false
        if (res.freeSecret) {
          freeSecret = res.freeSecret
        }

        this.setData({
          codeStatus: status,
          codeprice: res.CODEVALUE,
          extrainfo: res,
          freeSecret: freeSecret
        })

        this.dealBalance()
      }
      else {
        app.toast.error(res.MSG)
        if (this.data.extrainfo.CODEVALUE > 0) {
          this.setData({
            computeId: null,
            couponName: ''
          })
        }
        else {
          this.setData({
            codeStatus: 0,
            codeprice: 0
          })
        }
        if (this.data.extrainfo.PROMOTIONVALUE > 0) {
          this.setData({
            codeStatus: 0,
            codeprice: 0
          })
        }
        else {
          this.setData({
            computeId: null,
            couponName: ''
          })
        }
      }
    }
    else {
      if (res.success === true) {
        res = res.data
        res.PAYTATOL = keepTwoDecimalFull(res.payTotal)
        res.TOTALPRICE = keepTwoDecimalFull(res.totalPrice)
        res.DELIVERPAY = keepTwoDecimalFull(0)
        res.BALANCE = res.balance
        res.PAYBALANCE = res.payBalance
        if (res.PROMOTION) {
          var coupons = JSON.parse(res.PROMOTION)
          res.couponNum = coupons.AVAILABLEPROMOTIONS.length
        }
        else {
          res.couponNum = 0
        }
        if (!res.cashCardValue) {
          res.cashCardValue = 0
        }
        var freeSecret = false
        if (res.freeSecret) {
          freeSecret = res.freeSecret
        }
        this.setData({
          extrainfo: res,
          freeSecret: freeSecret
        })
        this.dealBalance()
      }
      else {
        if (this.data.extrainfo.cashCardValue <= 0) {
          this.setData({
            cardNo: null,
            cardPwd: null
          })
        }
      }
    }
  },
  dealBalance: function () {
    var balanceSum = 0
    if (this.data.extrainfo.PAYBALANCE > 0) {
      balanceSum = this.data.extrainfo.PAYBALANCE
    }
    else {
      if (this.data.extrainfo.BALANCE >= this.data.extrainfo.PAYTATOL) {
        balanceSum = this.data.extrainfo.PAYTATOL
      }
      else {
        balanceSum = this.data.extrainfo.BALANCE
      }
    }
    balanceSum = keepTwoDecimalFull(balanceSum)
    this.setData({
      balanceSum: balanceSum
    })
  },
  bindDateTimeColumnChange: function (e) {
    var timeIndex = this.data.timeIndex
    timeIndex[e.detail.column] = e.detail.value
    if (e.detail.column === 0) {
      if (ordertype === 'bread') {
        var dateTimeSets = this.data.dateTimeSets
        dateTimeSets[1] = timeChArr[e.detail.value]
        timeIndex[1] = 0
        var curTime = dateTimeSets[e.detail.column][e.detail.value]
        if (curTime && curTime.indexOf('45分钟极速送达') >= 0) {
          distype = 'IMMEDIATE'
        } else {
          distype = 'NORMAL'
        }
        this.setData({
          dateTimeSets: dateTimeSets
        })
      }
      else {
        var target_date = dateArr[e.detail.value]
        this.loadSendTime(target_date)
      }
    }
    this.setData({
      timeIndex: timeIndex
    })
  },
  changeAddr: function () {
    wx.showModal({
      title: '',
      content: '切换地址可能导致购物车中部分商品无效，是否继续？',
      confirmColor: '#a08257',
      confirmText: '是',
      cancelText: '否',
      success: function (res) {
        if (res.confirm) {
          wx.navigateTo({
            url: '../my/address/address?type=select',
          })
        }
      }
    })
  },
  cardInput: function (e) {
    var boardcard = e.detail.value
    boardcard = cutStringSum(boardcard)
    var index = e.currentTarget.dataset.cakeindex
    var goods = this.data.goods
    goods[index].boardcard = boardcard
    this.setData({
      goods: goods
    })
  },
  notesInput: function (e) {
    this.setData({
      usernotes: e.detail.value
    })
  },
  validBoardCard: function () {
    return this.data.goods.some(function (good) {
      return /^([\u4e00-\u9fa5]|[a-zA-Z0-9\s])+$/.test(good.boardcard)
    })
  },
  payOrder: function () {
    if (this.data.tipsOK !== '1') {
      app.toast.error('请同意面包收货协议')
      return
    }
    if (ordertype === 'bread') {
      this.breadPayOrder()
    }
    else {
      if (!this.validBoardCard()) {
        app.toast.error('巧克力牌请勿使用特殊字符')
      } else {
        this.cakePayOrder()
      }
    }
  },
  breadPayOrder: function () {
    var products = []
    var temp_products = []
    for (var i = 0; i < this.data.goods.length; i++) {
      var productinfo = {
        MEALID: this.data.goods[i].ID,
        COUNT: +this.data.goods[i].COUNT
      }
      var tempro = {
        id: this.data.goods[i].ID,
        num: +this.data.goods[i].COUNT
      }
      products.push(productinfo)
      temp_products.push(tempro)
    }

    var datas = {
      "uuid": UUID.uuidFast(), //前端生成唯一ID
      "DISPTYPE": "0", //配送方式，固定0
      "NOTIFYTIME": "8:00-9:00",//提醒时间，固定
      "CITY": this.data.address.CITYID,
      "ACTIVITYTRIGGER": "0",//固定值
      "STORENAME": "",//门店名称，固定值
      "POINTNAME": "0",//积分名称
      "CODENAME": this.data.codeval,//优惠码名称
      "ORDERSTARTDAY": breadType === '3' ? "TOMORROW" : "TODAY",
      "PRODUCTSCOUNT": this.data.totalcount,//数量
      "LOCATION": this.data.address.LOCATION,
      "CITYNAME": this.data.address.CITYNAME,
      "CITYID": this.data.address.CITYID,
      "RECEIVERMOBILE": this.data.address.RECEIVERMOBILE,
      "TOWNNAME": this.data.address.TOWNNAME,
      "RECEIVERNAME": this.data.address.RECEIVERNAME,
      "ISDEFAULT": this.data.address.ISDEFAULT,
      "TOWNID": this.data.address.TOWNID,
      "PROVINCENAME": this.data.address.PROVINCENAME,
      "COUNTYNAME": this.data.address.COUNTYNAME,
      "ADDRESS": this.data.address.ADDRESS,
      "LABEL": this.data.address.LABEL,
      "PROVINCEID": this.data.address.PROVINCEID,
      "COUNTYID": this.data.address.COUNTYID,
      "DISPTIME": timeArr[this.data.timeIndex[0]][this.data.timeIndex[1]],
      "DISP_DATE_ALIAS": dateChArr[this.data.timeIndex[0]],
      "ORDERS": [{
        "DISPDATE": dateArr[this.data.timeIndex[0]],
        "MEALS": products
      }],
      "TOTALPRICE": this.data.extrainfo.TOTALPRICE,//总体价格
      "DISPCOST": this.data.extrainfo.DELIVERPAY,//配送费用
      "TOPAY": this.data.extrainfo.PAYTATOL,//应付款
      "DISCOUNT": this.data.extrainfo.DISCOUNT,//优惠额
      "CODEVALUE": this.data.codeprice,//优惠码抵扣金额
      "DELIVERPAY": this.data.extrainfo.DELIVERPAY,//配送费用
      "PAYBALANCE": this.data.extrainfo.PAYBALANCE,//已使用原麦余额
      "freeSecret": this.data.extrainfo.freeSecret,//是否开启了免密支付
      "PAYTATOL": this.data.extrainfo.PAYTATOL,//应付款
      "DELIVERDESC": this.data.extrainfo.DELIVERDESC,
      "RESULT": this.data.extrainfo.RESULT,
      "BALANCE": this.data.extrainfo.BALANCE,

      "DISTYPE": distype,//配送类型
      "WEIXIN": this.data.extrainfo.PAYTATOL,//微信支付金额
      "PAYAMOUNT": this.data.extrainfo.PAYTATOL,
      "PROMOTIONINFO": [],//优惠券信息描述
      "usedResource": {
        "pointStatus": this.data.pointStatus,//0不使用积分,1选择使用积分
        "codeStatus": this.data.codeStatus,//是否使用优惠码
        "computeId": this.data.computeId,//选择卡券的唯一id
        "codeValue": this.data.codeval,//优惠码
        "showPromotion": false,
        "balanceStatus": this.data.balanceStatus,
        "meals": temp_products,
        "orderSource": ordersource
      },
      "MENUTYPE": ordersource
    }

    if (stationId) {
      datas["STATIONID"] = stationId //站点ID
    }

    if (storeId) {
      datas["STOREID"] = storeId //门店ID
    }

    var url = '/yuanmai_we/orders/orderform/create'
    var params = {
      datas: JSON.stringify(datas),
      __zaofans: true
    }
    app.showLoading()
    app.request(url, params).then(
      this.payOrderCallBack.bind(this),
      err => app.toast.error(err)
    ).finally(app.hideLoading)
  },
  payOrderCallBack: function (res) {
    app.globalData.needClearBreadCar = '1'
    if (res.payInfo.type === 'paysuccess') {
      app.toast.success('下单成功')
      setTimeout(() => {
        wx.redirectTo({
          url: '../my/order/order?ordertype=3'
        })
      }, 1000)
    } else {
      var order = encodeURIComponent(JSON.stringify(res))
      wx.redirectTo({
        url: '../pay/pay?entry=neworder&order=' + order,
      })
    }
  },
  cakePayOrder: function () {
    var products = []
    for (var i = 0; i < this.data.goods.length; i++) {
      var productinfo = {}
      productinfo.id = this.data.goods[i].ID
      productinfo.num = this.data.goods[i].num
      productinfo.remark = this.data.goods[i].boardcard
      productinfo.image = this.data.goods[i].image
      products.push(productinfo)
    }
    var useResource = {
      "pointStatusBB": true,
      "pointStatus": this.data.pointStatus,
      "codeStatus": 0,
      "computeId": this.data.computeId,
      "codeValue": null,
      "showPromotion": false,
      "balanceStatus": this.data.balanceStatus,
      "balanceStatusBB": true,
      "cardNo": this.data.cardNo,
      "cardPwd": this.data.cardPwd,
      "meals": products
    }
    var disptime = timeArr[this.data.timeIndex[1]] + '-' + timeArr[this.data.timeIndex[1]]
    var dispdate = dateArr[this.data.timeIndex[0]]
    var orderInfo = {
      "location": this.data.address.LOCATION,
      "cityName": this.data.address.CITYNAME,
      "cityId": this.data.address.CITYID,
      "receiverMobile": this.data.address.RECEIVERMOBILE,
      "receiverName": this.data.address.RECEIVERNAME,
      "countyName": this.data.address.COUNTYNAME,
      "address": this.data.address.ADDRESS,
      "countyId": this.data.address.COUNTYID,
      "dispTime": disptime,
      "dispDate": dispdate,
      "remark": this.data.usernotes,
      "stationId": stationId
    }
    var params = {
      useResource: JSON.stringify(useResource),
      orderInfo: JSON.stringify(orderInfo),
      __zaofans: true
    }
    app.showLoading()
    var url = '/yuanmai_we/mcake/order/create'
    app.request(url, params).then(
      this.cakePayOrderCallBack.bind(this),
      err => app.toast.error(err)
    ).finally(app.hideLoading)
  },
  cakePayOrderCallBack: function (res) {
    if (res.success === true) {
      app.globalData.needClearCakeCar = '1'
      if (res.data.payInfo.type === 'paysuccess') {
        app.toast.success('下单成功')
        setTimeout(() => {
          wx.redirectTo({
            url: '../my/order/order?ordertype=3'
          })
        }, 1000)
      } else {
        var cake = encodeURIComponent(JSON.stringify(this.data.goods))
        var payinfo = encodeURIComponent(JSON.stringify(res.data.payInfo))
        wx.redirectTo({
          url: '../pay/pay?entry=neworder&cake=' + cake + '&payinfo=' + payinfo,
        })
      }
    } else {
      app.toast.error('订单创建失败')
    }
  },
  inputKL: function (e) {
    var code = e.detail.value
    this.setData({
      codeval: code
    })
  },
  useKL: function () {
    if (!this.data.codeval) {
      return
    }
    if (this.data.computeId != null) {
      var that = this
      wx.showModal({
        title: '',
        content: '卡券和优惠码只能使用一个',
        confirmColor: '#a08257',
        confirmText: '确认',
        cancelText: '取消',
        success: function (res) {
          if (res.confirm) {
            that.didUseKL()
          }
        }
      })
    } else {
      this.didUseKL()
    }
  },
  didUseKL: function () {
    this.setData({
      codeStatus: 1
    })
    this.loadKLAndPrice()
  },
  showKL: KL.check,
  closeKL: KL.close
})
